package com.zhijian.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhijian.entity.ChatMessage;
import com.zhijian.entity.R;
import com.zhijian.service.IChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/chatMessage")
public class ChatMessageController {

    @Autowired
    private IChatMessageService chatMessageService;

    @GetMapping("/history")
    public R getHistoryMessages(
            @RequestParam String userId,
            @RequestParam(required = false) String customerId,
            @RequestParam(defaultValue = "20") Integer limit) {
            
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        // 获取双方对话记录
        queryWrapper.nested(w -> w
                .eq("fromUserId", userId).eq("toUserId", customerId)
                .or()
                .eq("fromUserId", customerId).eq("toUserId", userId))
            .orderByDesc("sendTime")
            .last("LIMIT " + limit);
            
        List<ChatMessage> messages = chatMessageService.list(queryWrapper);
        return R.ok().put("messages", messages);
    }

    @GetMapping("/offline")
    public R getOfflineMessages(@RequestParam String userId) {
        List<ChatMessage> messages = chatMessageService.getOfflineMessages(userId);
        return R.ok().put("data", messages);
    }

    @PostMapping("/read/{messageId}")
    public R markAsRead(@PathVariable Long messageId) {
        chatMessageService.markMessageAsRead(messageId);
        return R.ok();
    }

    @PostMapping("/save")
    public R saveMessage(@RequestBody ChatMessage message) {
        chatMessageService.saveMessage(message);
        return R.ok();
    }
} 